package com.taiyuan.ty.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taiyuan.ty.common.R;
import com.taiyuan.ty.entity.Comment;
import com.taiyuan.ty.entity.Place;
import com.taiyuan.ty.service.CommentService;
import com.taiyuan.ty.service.PlaceService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author : 周桓宇
 * @description : 地点管理
 * @createDate : 2025/3/25 下午2:48
 */
@RestController
@RequestMapping("/api/place")
public class PlaceController {
    @Autowired
    private PlaceService placeService;

    @Autowired
    private CommentService commentService;

    /**
     * 添加地点
     * @param place
     * @return
     */
    @PostMapping("/create")
    public R<String> save(@RequestBody Place place) {
        if (place.getCreateTime() == null) {
            place.setCreateTime(new Date()); // 如果 createTime 为空，则设置为当前时间
        }
        if (placeService.save(place)) {
            return R.success("添加地点成功");
        } else {
            return R.error("添加地点失败");
        }
    }


    /**
     * 分页查询地点
     * @param page 页码  pageSize 每页数量
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        Page<Place> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Place> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Place::getId);

        placeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改地点
     * @param place
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody Place place) {
        placeService.updateById(place);
        return R.success("修改成功");
    }


    /**
     * 删除地点
     * @param id
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        if (placeService.removeById(id)) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @GetMapping("/{id}")
    public Map<String, Object> getPlaceDetails(@PathVariable Long id) {
        Place place = placeService.getPlaceById(id);
        List<Comment> comments = commentService.getCommentsByPlaceId(id);
        Map<String, Object> result = new HashMap<>();
        result.put("place", place);
        result.put("comments", comments);

        return result;
    }

}